package cn.org.xiaosheng.utils;


import cn.org.xiaosheng.bean.Logs;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.SignStyle;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author XiaoSheng
 * @date 2024/9/9 下午11:58
 */
public class LogExtractor {

    public static void main(String[] args) {
//        String logLine = "27.18.107.54|-|[09/Sep/2024:23:10:12 +0800]|\"GET /interview/ HTTP/1.1\"|304|0|\"-\"|\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36\"|\"-\"";
//        String logLine = "27.18.107.54|-|[09/01/2024:23:10:12 +0800]|\"GET /interview/ HTTP/1.1\"|304|0|\"-\"|\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36\"|\"-\"";
        String logLines = """
                27.18.27.51|||-|||[10/Sep/2025:10:17:56 +0800]|||"GET /favicon.ico HTTP/1.1"|||500|||579|||"https://www.xiaosheng.org.cn/logs/renewLogs"|||"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"|||"-"|||
                """;
        extractLogInfo(logLines);
    }

    public static HashMap<String, String> monthMap = new HashMap<>();

    static {
        monthMap.put("jan", "01");
        monthMap.put("feb", "02");
        monthMap.put("mar", "03");
        monthMap.put("apr", "04");
        monthMap.put("may", "05");
        monthMap.put("jun", "06");
        monthMap.put("jul", "07");
        monthMap.put("aug", "08");
        monthMap.put("sep", "09");
        monthMap.put("oct", "10");
        monthMap.put("nov", "11");
        monthMap.put("dec", "12");
    }

    public static Logs extractLogInfo(String logLine) {


        // 定义正则表达式模式匹配|||分隔的字段
        Pattern pattern = Pattern.compile("([^|]*)\\|{3}");
        Matcher matcher = pattern.matcher(logLine);
        int count = 0;
        // 实例化需要保存的日志对象
        Logs logs = new Logs();
        while (matcher.find()) {
            // 提取每个字段
            String field = matcher.group(1).trim();
            switch (count) {
                case 0:
                    logs.setIpAddr(field);
                    break;
                case 1:
                    break;
                case 2:
                    // 使用正则表达式提取时间戳
                    // 处理时间戳字段（从匹配到的字段中提取，而非重新split）
                    String timestamp = field.replaceAll("[\\[\\]]", "").trim();
                    if (StringUtils.isEmpty(timestamp)) {
                        continue;
                    }
                    String[] parts = timestamp.split("/");
                    String month = parts[1];
                    // 替换月份缩写为数字
                    String monthNumber = monthMap.get(month.toLowerCase());
                    // 构建新的时间戳字符串
                    String newTimestamp = parts[0] + "/" + monthNumber + "/" + parts[2];
                    LocalDateTime localDateTime = convertToLocalDateTime(newTimestamp);
                    logs.setAccessTime(localDateTime);
                    break;
                case 3:
                    logs.setSimpleRequest(field.replaceAll("\"", ""));
                    break;
                case 4:
                    logs.setRequestNum(field);
                    break;
                case 5:
                    if (field.equals("'") || field.equals("") || null == field) {
                        logs.setBodyLength(0L);
                    } else {
                        logs.setBodyLength(Long.parseLong(field));
                    }
                    break;
                case 6:
                    break;
                case 7:
                    logs.setHttpAgent(field.replaceAll("\"", ""));
                    break;
                case 8:
                    System.out.println("Additional Info: " + field.replaceAll("\"", ""));
                    break;
                default:
                    break;
            }
            count++;
            System.out.println(logs);

        }
        logs.setIsImportant(isImportantLogic(logs));
        return logs;
    }

    public static LocalDateTime convertToLocalDateTime(String timestamp) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy:HH:mm:ss Z");

        // 解析为 ZonedDateTime
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(timestamp, formatter);

        // 转换为 LocalDateTime
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();

        System.out.println("ZonedDateTime: " + zonedDateTime);
        System.out.println("LocalDateTime: " + localDateTime);
        // 解析日期时间字符串
        return localDateTime;
    }

    /**
     * 鉴定是否为重要访问数据
     * 有效数据如下:
     * 1.微信内置浏览器访问
     * 2.访问正常的interview路径页面
     * 3.含有其他重要信息
     */
    private static Integer isImportantLogic(Logs logs) {
        // 1, 微信内置浏览器访问
        if (logs.getHttpAgent().contains("MicroMessenger") || logs.getHttpAgent().contains("WeChat") || logs.getHttpAgent().contains("WeiXin")) {
            return 1;
        }
        // 2.访问正常的interview路径页面
        if (logs.getSimpleRequest().contains("interview")) {
            return 1;
        }
        // 3.含有其他重要信息
        return 0;
    }
}
